<template>
  <!--elrow和elcol，左边300px，其余是右边-->
  <el-row :gutter="12" v-loading="loading">
    <el-col :span="6">
      <el-form label-position="top" label-width="auto" style="max-width: 600px">
        <el-form-item label="数据源名称" prop="name">
          <!-- <el-input v-model="datasetForm.name" placeholder="请输入数据源名称" /> -->
          <el-select v-model="currentDsId" :disabled=true placeholder="请选择数据源名称" clearable @change="handleSelect">
            <el-option v-for="item in dbList" :key="item.id ?? ''" :label="item.name" :value="item.id ?? ''" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据表" prop="tableName">
          <el-input v-model="datasetForm.dbName" placeholder="请输入数据表名称">
            <template #prefix>
              <Icon icon="ep:search" />
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div :style="{ height: '60vh', overflow: 'auto' }">
        <el-table :data="tableList" style="width: 100%">
          <el-table-column prop="tableName" show-overflow-tooltip label="表名" min-width="180">
            <template #default="{ row }">
              <div>
                <span :title="row.tableName" style="width: 120px">
                  {{ '&nbsp;' + row.tableName }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="tableDescription" show-overflow-tooltip label="表描述" min-width="180">
            <template #default="{ row }">
              <div>
                <span :title="row.tableDescription" style="width: 120px">
                  {{ '&nbsp;' + row.tableDescription }}
                </span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-col>
    <el-col :span="18">
      <el-row>
        <el-col :span="24">
          <!--运行sql，参数配置，保存-->
          <el-row :gutter="20" style="margin-bottom: 8px;">
            <el-col :span="24">
              <el-button @click="handleRun" type="primary">运行</el-button>
              <el-button plain>参数配置</el-button>
              <el-button plain @click="saveDsTable">保存</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <CodeMirror v-model:code="code" dark :codeStyle="{ width: '100%', height: '300px', fontSize: '16px' }"
                @ready="onReady" @change="onChange" @focus="onFocus" @blur="onBlur" />
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-table :data="tableDataList" style="height:40vh; width: 100%">
            <el-table-column show-overflow-tooltip v-for="(column, index) in columns" :key="index" :prop="column.name"
              :label="column.comment" :min-width="150" :fixed="columns.length - 1 === index ? 'right' : false">
              <template #header>
                <div class="flex-align-center">
                  <Icon :icon="getIcon(column.type)" />
                  <span :title="column.comment" style="width: 120px">
                    {{ '&nbsp;' + column.comment }}
                  </span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import { ElTree } from 'element-plus'
// const { t } = useI18n()

import * as DsApi from '@/api/data/ds/index'
import * as DsCategoryApi from '@/api/data/dscategory/index'
import * as DsTableApi from '@/api/data/dstable/index'
import { onMounted, onBeforeMount } from 'vue'
import { id } from 'element-plus/es/locale'
const message = useMessage() // 消息弹窗
defineOptions({ name: 'DsEditor' })

const loading = ref(false)
const deptName = ref('')
const dbList = ref<DsCategoryApi.DsCategoryVO[]>([]) //
const treeRef = ref<InstanceType<typeof ElTree>>()
const code = ref('')
const currentDsId = ref(0) // 当前选中的数据源ID
const tableList = ref<{ id: string; tableName: string }[]>([])
const optType = ref('') // 操作类型
//动态列头
const columns = ref<Array<{ name: string; comment?: string; type?: string }>>([

])

//动态表格数据
const tableData = ref({})
const tableDataList = ref<Array<Record<string, any>>>([])



function onReady(payload: any) {
  // console.log('ready', payload)
}
function onChange(value: string, viewUpdate: any) {
  // console.log('change', value)
  // console.log('change', viewUpdate)
}
function onFocus(viewUpdate: any) {
  // console.log('focus', viewUpdate)
}
function onBlur(viewUpdate: any) {
  // console.log('blur', viewUpdate)
}

const datasetForm = reactive<{
  id: number | undefined, // 编号
  name: string, // 名称
  description: string, // 描述
  type: string, // 类型
  pid: number | undefined, // 父级ID
  ip: string, // IP地址
  port: string, // 端口
  dbName: string
}>({
  id: undefined, // 编号
  name: "", // 名称
  description: "", // 描述
  type: "", // 类型
  pid: undefined,// 父级ID
  ip: "", // IP地址
  port: "", // 端口
  dbName: ""
})

//DsTableVO
const formData = reactive<{
  id: number | undefined, // 编号
  name: string, // 名称
  description: string, // 描述
  tableName: string, // 类型
  datasourceId: number | undefined,
  datasetGroupId: number | undefined,
  type: string, // db,sql,union,excel,api
  info: string, // 表原始信息,表名,sql等
  sqlVariableDetails: string
}>({
  // id is optional for creation, so we omit it or ensure it's a number when needed
  id: undefined, // 编号
  name: "", // 名称
  description: "", // 描述
  tableName: "", // 物理表名
  datasourceId: 0 as number, // 数据源ID
  datasetGroupId: 0 as number, // 数据集ID
  type: "", // db,sql,union,excel,api
  info: "", // 表原始信息,表名,sql等
  sqlVariableDetails: "" // SQL参数
})

const handleRun = () => {
  loading.value = true
  DsApi.DsApi.previewSql({
    sql: code.value,
    dsId: currentDsId.value
  }).then((res) => {
    console.log('res', res)
    columns.value = res.cols;
    tableData.value = res.data;
    genTableData()
    loading.value = false
  }).catch((err) => {
    console.error('err', err)
    loading.value = false
  })
}

/** 打开弹窗 */
const open = async (type: string, id?: number, dsId?: number) => {
  console.log('open', type, id, dsId)
  //create - 新增；update - 修改
  loading.value = true
  optType.value = type

  if (dsId) {
    formData.datasourceId = dsId
    currentDsId.value = dsId
    handleSelect(dsId.toString())
  }

  // 修改时，设置数据
  if (id) {
    try {
      Object.assign(formData, await DsTableApi.DsTableApi.getDsTable(id))
      if (formData.info) {
        const info = JSON.parse(formData.info)
        console.log('info', info)
        // 赋值
        code.value = info.sql
      }

      console.log('formData', formData)
    } finally {
      // loading.value = false
    }
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

//根据columns和tableData动态生成表格数据
const genTableData = () => {
  const data: Array<Record<string, any>> = []
  if (!tableData.value) {
    return
  }
  for (let i = 0; i < columns.value.length; i++) {
    const column = columns.value[i]
    const colData = tableData.value[column.name]
    for (let j = 0; j < colData.length; j++) {
      const row = data[j] || {}
      row[column.name] = colData[j]
      data[j] = row
    }
  }
  console.log('data', data)
  tableDataList.value = data
}

//获取表数据
const handleSelect = (val: string) => {
  loading.value = true
  DsCategoryApi.DsCategoryApi.getTableListByDsId({
    dsId: val
  }).then((res) => {
    tableList.value = res
    loading.value = false
  }).catch((err) => {
    loading.value = false
    console.error('err', err)
  })
}

/** 获得数据源 */
const getDsCategoryList = async () => {
  const res = await DsCategoryApi.DsCategoryApi.getDsCategoryList();
  dbList.value = []
  dbList.value.push(...res)
  // console.log('dbList', dbList.value)
}


const getIcon = (type) => {
  switch (type) {
    case 'datetime':
      return 'ep:clock'
    case 'string':
      return 'ep:document'
    case 'number':
      return 'fa:tag'
    default:
      return 'ep:document'
  }
}


/**
 * 保存数据集
 */
const saveDsTable = () => {
  console.log('saveDsTable', formData)
  let sql = code.value;
  let info = {
    sql: sql
  }

  //拼凑数据
  let submitData: any = { ...formData };
  if (optType.value === 'create') {
    // omit id for creation
    delete submitData.id;
  } else {
    // ensure id is a number for update

  }
  submitData.info = JSON.stringify(info);
  if (optType.value === 'create') {
    DsTableApi.DsTableApi.createDsTable(submitData).then((res) => {
      message.success('保存成功')
    }).catch((err) => {
      console.error('err', err)
      message.error('保存失败')
    })
  } else {
    DsTableApi.DsTableApi.updateDsTable(submitData).then((res) => {
      message.success('修改成功')
    }).catch((err) => {
      console.error('err', err)
      message.error('修改失败')
    })
  }

}

const emits = defineEmits(['node-click'])

/** 监听deptName */
watch(deptName, (val) => {
  treeRef.value!.filter(val)
})

/** 初始化 */
onMounted(() => {
  getDsCategoryList();
  genTableData();
})

// Not needed since we're using the Composition API lifecycle hooks
</script>
<style lang="scss" scoped>
.icon-methods {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-size: 20px;
  font-weight: 500;
  color: var(--TextPrimary, #1f2329);
  padding-bottom: 16px;

  .title {
    margin-right: auto;
    font-size: 16px;
    font-style: normal;
    font-weight: 500;
    line-height: 24px;
  }

  .custom-icon {
    font-size: 20px;

    &.btn {
      color: var(--ed-color-primary);
    }

    &:hover {
      cursor: pointer;
    }
  }
}

.flex-align-center {
  display: flex;
  align-items: center;

  &.icon {
    .ed-icon {
      margin-right: 6px;
    }
  }
}

.custom-icon {
  &.btn {
    color: var(--ed-color-primary);
  }

  &:hover {
    cursor: pointer;
  }
}
</style>
